package com.cjzuji.rental.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cjzuji.rental.mapper.UserMapper;
import com.cjzuji.rental.curl.HttpUrlConnectionExample;
import com.cjzuji.rental.pojo.UserData;
import com.cjzuji.rental.service.UserService;
import lombok.val;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
//http://127.0.0.1:9099/tool/user
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    private HttpUrlConnectionExample HttpUrlConnectionExample;
    @Autowired
    SqlSessionFactory sqlSessionFactory;

    @Override
    @Transactional
    public void add(UserData userData) {
        try {
            String count = HttpUrlConnectionExample.sendCurlRequest("https://manage-api.qnvipmall.com/merchant/loan/v2/list",
                    "POST",
                    "{\"fundAuthTypes\":[],\"model\":\"transferAllList\",\"pageNo\":0,\"pageSize\":5,\"sendTypeFlag\":[],\"transferMerchantTag\":2}");
            //将list遍历  获取 map  根据map中的 id 获取订单详情
            // count是返回的JSON字符串
            if (!count.isEmpty()) {
                // 解析JSON字符串转为对象
                JSONObject jsonResponse = JSON.parseObject(count);
                // 从jsonResponse对象中通过方法获取data对象（getJSONObject）
                JSONObject jsonData = jsonResponse.getJSONObject("data");
                System.out.println("JSONObject ====:" + jsonData);
                // 通过方法（getJSONArray）获取list数组
                JSONArray jsonArray = jsonData.getJSONArray("list");
                //获取code，success，message
                String success = jsonResponse.getString("success");
                if (success == "true") {
                    System.out.println("成功"+success);
                    // 循环遍历list数组
                    for (int i = 0; i < jsonArray.size(); i++) {
                        // 获取list数组中的每个元素但是是字符串
                        String item = jsonArray.getString(i);
                        // 这个时候要转为对象(JSON.parseObject)
                        JSONObject jsonItem = JSON.parseObject(item);
                        //查询https://manage-api.qnvipmall.com/merchant/loan/log/dese/v2
                        //name
                        //receiverMobile
                        //receiverAddressFormat

                        // 获取id通过方法（getString）
                        String id = jsonItem.getString("id");//19218580
                        System.out.println("id:" + id);
                        System.out.println("idcardNo:" + jsonItem.getString("idcardNo"));
                        UserData userData1 = new UserData();

                        System.out.println("jsonItem" + jsonItem);
                        System.out.println(userData1.toString());
//                    userData1.setId(jsonItem.getLong("id"));
//                    userData1.setIdCard(jsonItem.getString("idcardNo"));
                        userData1.setIdCard("测试");
                        userData1.setReceiverName(jsonItem.getString("receiverName"));
                        userData1.setRentName(jsonItem.getString("encrName"));
                        userData1.setReceiverMobile(jsonItem.getString("receiverMobile"));
                        userData1.setMobile(jsonItem.getString("mobile"));
                        userData1.setReceiverAddress(jsonItem.getString("receiverAddress"));
//                    userData1.setIdCardBack(jsonItem.getString("idcardBackImgUrl"));
//                    userData1.setIdCardImg(jsonItem.getString("idcardImgUrl"));
//                    userData1.setFaceImg(jsonItem.getString("faceImgUrl"));
                        userData1.setIdCardBack("测试");
                        userData1.setIdCardImg("测试");
                        userData1.setFaceImg("测试");
                        System.out.println("userData1" + userData1.toString());
//                        userMapper.save(userData1);
                    }

                }
            }
        } catch (Exception e) {
            // 必须抛出异常才会触发事务回滚
            throw new RuntimeException("保存数据失败", e);
        }


    }


    // 请求外部接口将数据保存到数据库中
    @Override
    @Transactional
    public void external () {
        try {
            String count = HttpUrlConnectionExample.sendCurlRequest("https://manage-api.qnvipmall.com/merchant/loan/v2/list",
                    "POST",
                    "{\"fundAuthTypes\":[],\"model\":\"transferAllList\",\"pageNo\":0,\"pageSize\":5,\"sendTypeFlag\":[],\"transferMerchantTag\":2}");
            //将list遍历  获取 map  根据map中的 id 获取订单详情
            // count是返回的JSON字符串
            if (!count.isEmpty()) {
                // 解析JSON字符串转为对象
                JSONObject jsonResponse = JSON.parseObject(count);
                // 从jsonResponse对象中通过方法获取data对象（getJSONObject）
                JSONObject jsonData = jsonResponse.getJSONObject("data");
                System.out.println("JSONObject ====:" + jsonData);
                // 通过方法（getJSONArray）获取list数组
                JSONArray jsonArray = jsonData.getJSONArray("list");
                //获取code，success，message
                String success = jsonResponse.getString("success");
                if (success == "true") {
                    System.out.println("成功"+success);
                    // 循环遍历list数组
                    for (int i = 0; i < jsonArray.size(); i++) {
                        // 直接获取JSONObject
                        JSONObject jsonItem = jsonArray.getJSONObject(i);
                        UserData userData1 = new UserData();
                        // 获取id通过方法（getString）
//                        String id = jsonItem.getString("id");//19218580
//                        System.out.println("id:" + id);
                        System.out.println("idcardNo：" + jsonItem.getString("idcardNo"));

                        System.out.println("jsonItem" + jsonItem);
                        userData1.setId(jsonItem.getLong("id"));
//                    userData1.setIdCard(jsonItem.getString("idcardNo"));
                        userData1.setIdCard("测试");
                        userData1.setReceiverName(jsonItem.getString("receiverName"));
                        userData1.setRentName(jsonItem.getString("encrName"));
                        userData1.setReceiverMobile(jsonItem.getString("receiverMobile"));
                        userData1.setMobile(jsonItem.getString("mobile"));
                        userData1.setReceiverAddress(jsonItem.getString("receiverAddress"));
//                    userData1.setIdCardBack(jsonItem.getString("idcardBackImgUrl"));
//                    userData1.setIdCardImg(jsonItem.getString("idcardImgUrl"));
//                    userData1.setFaceImg(jsonItem.getString("faceImgUrl"));
                        userData1.setIdCardBack("测试");
                        userData1.setIdCardImg("测试");
                        userData1.setFaceImg("测试");
                        System.out.println("userData1" + userData1.toString());
                        int saveNumber = userMapper.externalSave(userData1);
                        System.out.println("saveNumber:" + saveNumber);
                        // 手动提交当前事务（确保SQL执行）
                        if(saveNumber > 0) {
                            SqlSession sqlSession = sqlSessionFactory.openSession();
                            try {
                                sqlSession.commit();
                            } finally {
                                sqlSession.close();
                            }
                        }
                    }

                }
            }
        } catch (Exception e) {
            // 必须抛出异常才会触发事务回滚
            throw new RuntimeException("保存数据失败", e);
        }
    }

    // 通过id查询详情
    public UserData getUserById (Long id) {
        UserData userData = userMapper.selectUserDataById(id);
        return userData;
    }

//    @Transactional
//    public UserData getUser(long id) {
//        return userMapper.findById(id);
//
//    }

//    public UserData edit(UserData userData) {
//        // 先检查用户是否存在
//        if (userMapper.selectById(userData.getId()) == null) {
//            throw new RuntimeException("用户不存在");
//        }
//        // 执行更新
//        int affected = userMapper.update(userData);
//        if (affected == 0) {
//            throw new RuntimeException("更新失败");
//        }
//        // 返回更新后的数据
//        return userMapper.findById(userData.getId());
//    }


}